package com.arpa.ntocc.basic.api.service.impl;

import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.OBSUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.entity.PartyGroupConfig;
import com.arpa.ntocc.common.mapper.PartyGroupConfigMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传service
 * @Author liuyj
 * @Date 2019-12-10 16:24:27
 */
@Service
@Log4j2(topic = "business")
public class FileUploadService {

    @Autowired
    PartyGroupConfigMapper partyGroupConfigMapper;

    /**
     * 上传文件
     * @param myFiles
     * @return
     * @throws IOException
     */
    public Result uploadFile(MultipartFile[] myFiles) throws IOException {
        if( myFiles==null || myFiles.length==0 ){
            return Result.error("上传文件不能为空");
        }
        //查询文件上传黑名单
        PartyGroupConfig partyGroupConfig = partyGroupConfigMapper.selectOne(new QueryWrapper<PartyGroupConfig>().lambda()
                .eq(PartyGroupConfig::getType,"fileBlackList")
                .eq(PartyGroupConfig::getBranchCode, UserUtil.getBranchCode())
                .eq(PartyGroupConfig::getConfigKey,"fileBlackList"));
        if(partyGroupConfig==null || StringUtils.isBlank(partyGroupConfig.getConfigValue())){
            return Result.error("请通知管理员维护文件上传类型黑名单");
        }
        List<String> list = new ArrayList<String>();
        for (MultipartFile myFile : myFiles) {
            // 上传文件 ,
            if (myFile.isEmpty()) {
                log.error("上传文件为空");
                continue;
            } else {
                //校验文件上传类型黑名单
                if(inBlackList(myFile,partyGroupConfig.getConfigValue())){
                    return Result.error("禁止上传改文件类型文件");
                }
                String path = OBSUtil.uploadFile(myFile);
                list.add(path);
            }
        }
        //替换掉空格、"["、"]"
        String paths = list.toString().replaceAll("[\\s]|[\\[]|[\\]]", "");
        return Result.ok("上传成功").data(paths);
    }

    /**
     * 判断上传文件是否在文件上传黑名单中
     * @param myFile
     * @param fileBlackList
     * @return
     */
    private boolean inBlackList(MultipartFile myFile,String fileBlackList) {
        boolean flag=false;
        if(StringUtils.isNotEmpty(fileBlackList)){
            String fileName = myFile.getOriginalFilename();
            String suffix= CommonUtil.fileSuffix(fileName);
            if(fileBlackList.indexOf(suffix)>=0){
                flag=true;
            }
        }
        return flag;
    }
}
